# coding=UTF-8
import arcpy as ap
from arcpy import env
import os
import io

#转为二进制文件
def ToASC(T_filepath,F_filepath):
    if not os.listdir('T_ASCII') and not os.listdir('F_ASCII'):
        for name in os.listdir(T_filepath):
            if os.path.splitext(name)[1]=='.TIF':
                env.workspace = r"G:\tif\T_ASCII"
                ap.RasterToASCII_conversion('T_extent'+os.sep+name,os.path.splitext(name)[0]+'.asc')
        for name in os.listdir(F_filepath):
            if os.path.splitext(name)[1]=='.TIF':
                env.workspace = r"G:\tif\F_ASCII"
                ap.RasterToASCII_conversion('F_extent'+os.sep+name,os.path.splitext(name)[0]+'.asc')
    else: 
        print('二进制文件夹非空！')    
#通过替换二进制文件修改放射变换参数
def rpaffine(T_file,F_file):
    f = io.open('./T_ASCII/'+T_file,'r',encoding='utf-8')
    T_lines = f.readlines()[:6]
    f.close()
    f = io.open('./F_ASCII/'+F_file,'r',encoding='utf-8')
    F_lines = f.readlines()[6:]
    f.close()
    with io.open('./T_ASCII/'+F_file,'w',encoding='utf-8') as f: 
        f.writelines(T_lines+F_lines)               
    f.close()
#修改错误二进制文件
def change(T_filepath,F_filepath):
    for T_name in os.listdir(T_filepath):
        if os.path.splitext(T_name)[1]=='.asc':
            for F_name in os.listdir(F_filepath):
                if os.path.splitext(T_name)[1]=='.asc' and T_name==F_name:
                    rpaffine(T_name,F_name)
#转二进制文件至TIFF
def TOGTIFF(T_filepath):
    if not os.listdir(r"G:\tif\change_TIFF"):  
        if  os.listdir('T_ASCII'):
            for name in os.listdir(T_filepath):
                if os.path.splitext(name)[1]=='.asc':                                                    
                    env.workspace = r"G:\tif\change_TIFF"
                    infc = os.path.splitext(name)[0]+'.tif'
                    ap.ASCIIToRaster_conversion(os.getcwd()+os.sep+'T_ASCII'+os.sep+name,infc,'FLOAT')
                    #sr = ap.SpatialReference("WGS_1984_UTM_Zone_50N")
                    Coordinate_System =r'T_ASCII\dandou0.prj'
                    ap.DefineProjection_management(infc, Coordinate_System)
        else: 
            print('二进制文件夹为空！')  
    else: 
        print('change_TIFF文件夹非空！')  

if __name__ == "__main__":
    ToASC('T_extent','F_extent')
    change('T_ASCII','F_ASCII')
    TOGTIFF('T_ASCII')